package model

import (
	"context"
	"fmt"

	"github.com/apache/rocketmq-client-go/v2"
	"github.com/apache/rocketmq-client-go/v2/primitive"
	"github.com/apache/rocketmq-client-go/v2/producer"
)

// 延迟消息生产者
func Produce(content, topic, group string) error {
	var p, _ = rocketmq.NewProducer(
		producer.WithNsResolver(primitive.NewPassthroughResolver([]string{"127.0.0.1:9876"})),
		producer.WithRetry(2),
		producer.WithGroupName(group),
	)
	err := p.Start()
	if err != nil {
		return fmt.Errorf("start producer error: %s", err.Error())
	}

	msg := &primitive.Message{
		Topic: topic,
		Body:  []byte(content),
	}

	// 设置消息延迟时间为1分钟
	//delayLevel := 5 // 1分钟对应的延迟级别，根据具体业务需求调整
	//
	//msg.WithDelayTimeLevel(delayLevel)

	res, err := p.SendSync(context.Background(), msg)

	if err != nil {
		return fmt.Errorf("send message error: %s\n", err)
	} else {
		fmt.Printf("send message success: result=%s\n", res.String())
	}

	err = p.Shutdown()
	if err != nil {
		return fmt.Errorf("shutdown producer error: %s", err.Error())
	}

	return nil
}
